
import re
from rest_framework.exceptions import ValidationError

# 编写一个邮箱正则验证器类
class EmailValidator:
    def __init__(self):
        self.pattern = re.compile(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$')

    def validate(self, email):
        if not self.pattern.match(email):
            raise ValidationError('邮箱格式错误')

    def __call__(self, email):
        self.validate(email)
        return
    
# 编写一个手机号码正则验证器类
class MobileValidator:
    def __init__(self):
        self.pattern = re.compile(r'^1[3-9]\d{9}$')

    def validate(self, mobile):
        if not self.pattern.match(mobile):
            raise ValidationError('手机号码格式错误')

    def __call__(self, mobile):
        self.validate(mobile)
        return
    
# 编写一个密码正则验证器类
class PasswordValidator:
    def __init__(self):
        self.pattern = re.compile(r'^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*?]).*$')

    def validate(self, password):
        if not self.pattern.match(password):
            raise ValidationError('密码最少6位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符')

    def __call__(self, password):
        self.validate(password)
        return

# 编写一个用户名正则验证器类
class NameValidator:
    def __init__(self):
        self.pattern = re.compile(r'^[a-zA-Z0-9_-]{3, 20}$')

    def validate(self, username):
        if not self.pattern.match(username):
            raise ValidationError('用户名格式错误')

    def __call__(self, username):
        self.validate(username)
        return
    
# 编写一个ID正则验证器类
class IDValidator:
    def __init__(self):
        self.pattern = re.compile(r'^[a-zA-Z0-9_-]{4,8}$')

    def validate(self, id):
        if not self.pattern.match(id):
            raise ValidationError('工号4到8位（字母，数字，下划线，减号）')

    def __call__(self, id):
        self.validate(id)
        return
    
# 中国身份证号码合法性验证类
class IDCardValidator:
    def __init__(self):
        self.pattern = re.compile(r'^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$')

    def validate(self, id_card):
        if not self.pattern.match(id_card):
            raise ValidationError('身份证号码格式错误')

    def __call__(self, id_card):
        self.validate(id_card)
        return


